package com.mxf.example.web.obs;


import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.mxf.example.entity.file.FileDocument;
import com.mxf.example.exception.BizException;
import com.mxf.example.service.obs.QCloudObsService;
import com.mxf.example.utils.http.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


@RestController
@RequestMapping(value = "/api/obs", produces = "application/json;charset=UTF-8")
@Api(value = "对象存储相关接口", tags = {"对象存储相关接口"})
public class FileController {
    @Autowired
    private QCloudObsService svr;

    @ApiOperation(value = "创建文件存储桶", notes = "创建文件存储桶")
    @GetMapping("/createBucket")
    public Result<String> createBucket(String bucketName) {
        return Result.createSuccess(svr.createBucket(bucketName));
    }

    @ApiOperation(value = "查询所有文件桶", notes = "查询所有文件桶")
    @GetMapping("/listBuckets")
    public Result<List> listBuckets() {
        return Result.createSuccess((List) svr.listBuckets());
    }

    @ApiOperation(value = "上传文件", notes = "上传文件")
    @PostMapping("/uploadFile")
    public Result<FileDocument> uploadFile(@RequestParam("file") MultipartFile file) {
        return Result.createSuccess(svr.createObject(file));
    }

    @ApiOperation(value = "下载文件", notes = "下载文件")
    @GetMapping("/download")
    public ResponseEntity<Object> download(String bucketName, String fileName) {
        FileDocument fileDocument = svr.getFileByte(bucketName, fileName);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=" + fileName)
                .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                .header(HttpHeaders.CONTENT_LENGTH, fileDocument.getFileSize() + "").header("Connection", "close")
                .body(fileDocument.getContent());
    }

    @ApiOperation(value = "删除文件", notes = "删除文件")
    @GetMapping("/removeFile")
    public Result removeFile(String fileName) {
        return Result.createSuccess(svr.deleteObject(fileName));
    }
}
